import { memo } from "react";
import { m } from "framer-motion";
import { Tooltip } from "shared/components";
import { EventTypeColorMaps } from "@/lib/constants";
import { IEventItem } from "@/lib/types";
import EventItem from "./EventItem";
import EndTextIcon from "@/assets/icons/end.svg?jsx";

type TimelineProps = {
  events: IEventItem[];
};

export default function Timeline(props: TimelineProps) {
  const { events } = props;

  return (
    <div className="md:px-8">
      {events.map((item, index) => (
        <TimelineEventItem key={index} event={item} />
      ))}
      {events.length > 0 && (
        <div className="mt-1 flex justify-center">
          <span className="rounded-full bg-[#AEDDA2]/[0.23] px-6 py-2 text-[#A4DBD3]">
            <EndTextIcon />
          </span>
        </div>
      )}
    </div>
  );
}

type TimelineEventItemProps = {
  event: IEventItem;
};
const TimelineEventItem = memo(
  function TimelineEventItem({ event }: TimelineEventItemProps) {
    console.log("render", event.id);
    return (
      <div
        id={`event-${event.id}`}
        className="group relative flex text-[#1E1E1E] even:flex-row-reverse"
      >
        <m.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true }}
          style={{
            color: EventTypeColorMaps[event.type] || EventTypeColorMaps["其他"],
          }}
          className="absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-[#A4DBD3]"
        >
          <Tooltip
            content={event.type || "其他"}
            placement="bottom"
            placementOffset={5}
            className="absolute left-1/2 top-1/2 block size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-current"
            contentClassName="text-[#5D6C6A] text-xs"
          />
        </m.div>

        <div className="flex flex-none basis-1/2 items-center justify-end p-4 group-even:justify-start">
          <m.span
            initial={{ opacity: 0 }}
            whileInView={{ opacity: 1 }}
            viewport={{ once: true }}
            className="relative rounded-sm bg-[#0B9682] px-2 py-1 text-sm text-white shadow-[0_6px_16px_0_rgba(0,0,0,0.08)] after:absolute after:right-0 after:top-1/2 after:size-2 after:-translate-y-1/2 after:translate-x-1/2 after:rotate-45 after:bg-inherit after:content-[''] group-even:after:left-0 group-even:after:right-[unset] group-even:after:-translate-x-1/2"
          >
            {event.time}
          </m.span>
        </div>
        <div className="flex-none basis-1/2 p-4">
          <EventItem event={event} />
        </div>
      </div>
    );
  },
  (prevProps, nextProps) => {
    return prevProps.event.id === nextProps.event.id;
    // return JSON.stringify(prevProps.event) === JSON.stringify(nextProps.event);
  },
);
